<template>
  <div class="users-wrapper">
    <!-- 搜索 -->
    <!-- <MySearch
      v-model="queryModel.query"
      @search="
        queryModel.pagenum = 1;
        getList();
      "
      @click="
        dialogFormVisible = true;
        model = {};
      "
    >
      添加用户
    </MySearch> -->
    <div class="search-wrapper">
      <el-input
        v-model="queryModel.query"
        class="input-with-select"
        placeholder="请输入搜索内容"
      >
        <template #append>
          <el-button @click="getList()"
            ><el-icon><Search /></el-icon
          ></el-button>
        </template>
      </el-input>
      <el-button
        type="primary"
        @click="
          dialogFormVisible = true;
          model = {};
        "
        >添加用户</el-button
      >
    </div>
    <!-- 表格 -->
    <!-- <Table ></Table> -->
    <Table
      :lists="list"
      :column="col"
      :total="total"
      :value="queryModel"
      @current="HandCurrent"
      @size="HandSize"
    >
      <template v-slot:state="{ row }">
        <el-switch
          v-model="row.mg_state"
          @change="getUpdataStatus(row.id, row.mg_state)"
        />
      </template>
      <template v-slot:action="{ row }">
        <el-button
          size="small"
          type="primary"
          @click="
            model = { ...row };
            dialogFormVisible = true;
          "
          >编辑</el-button
        >
        <el-button size="small" type="danger" @click="getdelUser(row.id)"
          >删除</el-button
        >
        <el-button
          size="small"
          type="warning"
          @click="
            model = { ...row };
            FormVisible = true;
            getRolesList();
          "
          >分配权限</el-button
        >
      </template>
    </Table>
    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="title"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addref"
        :model="model"
        :rules="rules"
        label-width="120px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="model.username" :disabled="!!model.id" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-show="!model.id">
          <el-input v-model="model.password" type="password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="model.email" />
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="model.mobile" maxlength="11" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="getAddUsers">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog
      v-model="FormVisible"
      title="分配权限"
      :close-on-click-modal="false"
    >
      <p>当前用户：{{ model.username }}</p>
      <br />
      <p>当前角色：{{ model.role_name }}</p>
      <br />
      <p>
        分配新角色:
        <el-select
          v-model="roleName"
          placeholder="请选择新角色"
          @change="RoleSId"
        >
          <el-option
            v-for="item in RolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="FormVisible = false">取消</el-button>
          <el-button type="primary" @click="getUpdataRoles(rid)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { reactive, toRefs, ref, onMounted, computed } from "vue";
import api from "@/http/api.js";
import { ElMessageBox, ElMessage } from "element-plus";

export default {
  name: "users",
  setup() {
    const addref = ref();
    /**
     * 定义数据
     */
    const state = reactive({
      rid: "",
      /**
       * 默认名
       */
      roleName: "",
      /**
       * 权限列表
       */
      RolesList: [],
      /**
       * 分配权限显示框
       */
      FormVisible: false,
      /**
       * 表单验证规则
       */
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "用户名的长度在2～10个字",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 18,
            message: "用户名的长度在6～18个字",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            type: "email",
            message: "请输入合法邮箱",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            message: "请输入正确手机号",
            trigger: "blur",
          },
        ],
      },
      /**
       * 添加模型
       */
      model: {},
      /**
       * 控制弹出框显示隐藏
       */
      dialogFormVisible: false,
      /**
       * 搜素数据
       */
      queryModel: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      /**
       * 总条数
       */
      total: 0,
      /**
       * 存储数据
       */
      list: [],
      /**
       * 表格配置项
       */
      col: [
        {
          type: "index",
          label: "",
        },
        {
          prop: "username",
          label: "姓名",
        },
        {
          prop: "email",
          label: "邮箱",
        },
        {
          prop: "mobile",
          label: "电话",
        },
        {
          prop: "role_name",
          label: "角色",
        },
        {
          slot: "state",
          label: "状态",
        },
        {
          label: "操作",
          slot: "action",
          width: 300,
        },
      ],
    });
    /**
     * 修改权限
     */
    let getUpdataRoles = async (rid) => {
      const res = await api.UpdataRoles(state.model.id, rid);
      if (res.meta.status == 200) {
        getList();
        state.FormVisible = false;
      }
    };
    /**
     * 获取角色ID
     */
    let RoleSId = async (value) => {
      state.rid = value;
      console.log(state.rid, "rid");
    };
    /**
     * 获取角色数据
     */
    let getRolesList = async () => {
      const res = await api.getRoles();
      console.log(res, 1111111);
      if (res.meta.status == 200) {
        state.RolesList = res.data;
        console.log(res.RolesList);
      }
    };
    /**
     * 修改状态
     */
    let getUpdataStatus = async (id, state) => {
      const res = await api.UpdataStatus(id, state);
      if (res.meta.state == 200) {
        state = !state;
        getList();
      }
    };
    /**
     * 删除用户
     */
    let getdelUser = (id) => {
      ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          console.log(id);
          const res = await api.delUser(id);
          // console.log(res, "row");
          if (res.meta.status == 200) {
            getList();
          }
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消删除",
          });
        });
    };
    /**
     * 添加用户
     */
    let getAddUsers = async () => {
      // const res = await api.getAddUser(state.model);
      // if (res.meta.status == 200) {
      //   state.dialogFormVisible = false;
      //   getList();
      // }

      const res = await (state.model.id ? api.UpdataUser : api.getAddUser)(
        state.model
      );

      if (res.meta.status == 200 || res.meta.status == 201) {
        state.dialogFormVisible = false;
        getList();
      }

      // addref.value.validate((valid) => {
      //   (state.model.id ? api.UpdataUser : api.getAddUser)(state.model).then(
      //     (res) => {
      //       if (valid) {
      //         if (res.meta.status == 200 || res.meta.status == 201) {
      //           state.dialogFormVisible = false;
      //           getList();
      //         }
      //       } else {
      //         console.log("error submit!!");
      //         return false;
      //       }
      //     }
      //   );
      // });
    };
    /**
     * 获取数据
     */
    let getList = async () => {
      const res = await api.getUserList(state.queryModel);
      console.log(res, "用户");
      if (res.meta.status == 200) {
        state.list = res.data.users;
        state.total = res.data.total;
      }
      console.log(state.list, 111);
    };

    let HandCurrent = (val) => {
      state.queryModel.pagenum = val;
      getList();
    };
    let HandSize = (val) => {
      state.queryModel.pagesize = val;
      getList();
    };

    onMounted(() => {
      getList();
    });
    /**
     * 标题
     */
    let title = computed(() => {
      return state.model.id ? "编辑用户 " : "添加用户";
    });

    return {
      ...toRefs(state),
      getList, //渲染
      getAddUsers, //添加 编辑 用户
      getdelUser, //删除用户
      getUpdataStatus, //修改状态
      getRolesList, //获取角色数据
      getUpdataRoles, //修改权限
      RoleSId, //获取角色Id
      addref, //ref
      title, //computed
      HandCurrent,
      HandSize,
    };
  },
};
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}

.users-wrapper {
  height: 100%;
  // 搜索盒子
  .search-wrapper {
    height: 50px;
    display: flex;
    align-items: center;
    .input-with-select {
      width: 400px;
      height: 40px;
      margin-right: 20px;
    }
  }
  // 表格
  .el-table {
    margin-top: 10px;
    margin-bottom: 15px;
  }
}
</style>